﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infratructure.Interfares;
using B.S.BaseData.Read.Api.Application.Command;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;

namespace B.S.BaseData.Read.Api.Application.CommandHander
{
    public class GetMenuCommandHander : IRequestHandler<GetMenuCommand, ApiResult<List<GetMenuDto>>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRequsitory<Menu> menuRequsitory;
        private readonly IBaseRequsitory<User> userRequsitory;

        public GetMenuCommandHander(IMapper mapper, IBaseRequsitory<Menu> menuRequsitory, IBaseRequsitory<User> userRequsitory)
        {
            this.mapper = mapper;
            this.menuRequsitory = menuRequsitory;
            this.userRequsitory = userRequsitory;
        }

        /// <summary>
        /// 显示菜单处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<GetMenuDto>>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<GetMenuDto>> result = new ApiResult<List<GetMenuDto>>();

            result.Code = ApiEnum.显示成功;
            result.Msg = ApiEnum.显示成功.ToString();

            var linq = from menu in menuRequsitory.GetAllAsync()
                       join user in userRequsitory.GetAllAsync() on menu.CreateBy equals user.UserId
                       select new GetMenuDto
                       {
                           Id = menu.Id,
                           MenuName = menu.MenuName,
                           Url = menu.Url,
                           PId = menu.PId,
                           CreateBy = menu.CreateBy,
                           CreateDate = menu.CreateDate,
                           UpdateBy = menu.UpdateBy,
                           UpdateDate = menu.UpdateDate,
                           UserName = user.UserName
                       };

            var entity = linq.OrderBy(x => x.Id).ToList();

            result.Data = mapper.Map<List<GetMenuDto>>(entity);

            return Task.FromResult(result);
        }
    }
}
